// Common/MiscUtilities.cpp

#include "StdAfx.h"

#include "MiscUtilities.h"

wchar_t Char2WHex(char x)
{
  if (x>=0 && x<=9)
    return x+L'0';

  if (x>=10 && x<=15)
    return x-10+L'a';

  return L'0';
}

char WHex2Char(wchar_t x)
{
  if (x>=L'0' && x<=L'9')
    return x-L'0';

  if (x>=L'a' && x<=L'f')
    return x-L'a'+10;

  if (x>=L'A' && x<=L'F')
    return x-L'A'+10;

  return 0;
}


void BytesToHexUString(UString &dst, char *src, int n)
{
  wchar_t *temp=dst.GetBuffer(2*n+1);
  for(int i=0; i<n; i++)
  {
    temp[2*i]=Char2WHex((src[i]>>4) & 0x0f);
    temp[2*i+1]=Char2WHex(src[i] & 0x0f);
  }
  temp[2*n]=0;
  dst.ReleaseBuffer();
}

void HexUStringToBytes(char *dst, UString src, int n)
{
  wchar_t *temp=src.GetBuffer(0);
  int j=0;
  for(int i=0; i<n; i+=2)
    dst[j++]=(WHex2Char(temp[i])<<4) | WHex2Char(temp[i+1]);
}
